from django.contrib import messages
from mainapp.views import kind
from django.shortcuts import redirect, render,reverse
from user.models import Kind, Article, Tag,User
from mainapp.models import VideosKinds
from .forms import ArticleForm,SigninForm,SignupForm,UpdateArticleForm
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.hashers import make_password
from django.contrib.auth.decorators import login_required
# Create your views here.


def index(request):
    articles = Article.objects.filter(
        permission='public').order_by('-post_datetime')
    kinds = Kind.objects.all()
    videos_kinds_name = VideosKinds.objects.all()
    return render(request, 'blog_article.html', {'articles': articles, 'kinds': kinds, 'videos_kinds_name': videos_kinds_name})


# def article_edit(request):
#     if request.method == "POST":

#         author = request.POST.get('author', '')
#         # id = request.POST.get('id')
#         title = request.POST.get('title', '')
#         content = request.POST.get('content_', '')
#         category = request.POST.get('category', '')
#         kind_pk = request.POST.get('kind', '')
#         kind = Kind.objects.get(pk=kind_pk)
#         tag_pk = request.POST.get('tag', '')
#         tag = Tag.objects.get(pk=tag_pk)
#         permission = request.POST.get('permission', '')
#         Article.objects.create(
#             author=author,
#             title=title,
#             content=content,
#             category=category,
#             kind=kind,
#             tag=tag,
#             permission=permission
#         )
#         return redirect('/')
#     else:
#         kinds = Kind.objects.all()
#         tags = Tag.objects.all()
#         videos_kinds_name = VideosKinds.objects.all()
#         return render(request, 'article_edit.html', locals())

def article_edit(request):
    if request.method == "POST":
        form = ArticleForm(request.POST)
        if form.is_valid():
            Article.objects.create(**form.cleaned_data)  # form.save()
            return redirect('/blog')
    else:
        kinds = Kind.objects.all()
        tags = Tag.objects. all()
        form = ArticleForm()
        videos_kinds_name = VideosKinds.objects.all()
        return render(request, 'article_edit.html', locals())



def blog_article_content(request, id):
    videos_kinds_name = VideosKinds.objects.all()
    kinds = Kind.objects.all()
    article = Article.objects.get(id=id)
    try:
        article.read_count += 1
        article.save()
    except:
        pass
    return render(request, 'blog_article_content.html', locals())



def blog_article_kind(request, id):
    articles = Article.objects.filter(kind=id, permission='public')
    kind = Kind.objects.get(id=id)
    kinds = Kind.objects.all()
    videos_kinds_name = VideosKinds.objects.all()
    return render(request, 'blog_article_kind.html', {'articles': articles, 'kinds': kinds, 'videos_kinds_name': videos_kinds_name, 'kind': kind})




def signin(request):
    videos_kinds_name = VideosKinds.objects.all()
    if request.method=='POST':
        form=SigninForm(request.POST)
        if form.is_valid():
            username=form.cleaned_data['username']
            password=form.cleaned_data['password']
            user=authenticate(username=username,password=password)
            if user:
                login(request,user)
                return redirect('/blog')
            else:
                message='账号或密码不正确'
        else:   
            message='检查表单是否填写正确'
    else:
        form=SigninForm()
    return render(request,'signin.html',locals())




def signup(request):
    videos_kinds_name = VideosKinds.objects.all()
    if request.method=='POST':
        form=SignupForm(request.POST)
        if form.is_valid():
            username=form.cleaned_data['username']
            nickname=form.cleaned_data['nickname']
            password=form.cleaned_data['password']
            password=make_password(password)
            User.objects.create(username=username,nickname=nickname,password=password)
            return redirect('/blog')
        message='检查表单是否填写正确'
        return render(request,'signup.html',locals())
    else:
        form=SignupForm()
        return render(request,'signup.html',locals())



def user_logout(request):
    logout(request)
    return redirect('/blog')



@login_required(login_url='/signin/')
def my_blog(request):
    videos_kinds_name = VideosKinds.objects.all()
    articles=Article.objects.filter(author=request.user)
    return render(request,'my_blog.html',locals())




@login_required(login_url='/signin/')
def delete_article(request,id):
    try:
        article=Article.objects.get(id=id)
        article.delete()
        messages.add_message(request,messages.SUCCESS,f'文章 {article.title} 删除成功')
    except:
        messages.add_message(request,messages.WARNING,'删除失败')
    return redirect(reverse('my_blog-url'))




@login_required(login_url='/signin/')
def update_article(request,id):
    videos_kinds_name = VideosKinds.objects.all()
    if request.method=='POST':
        form=UpdateArticleForm(request.POST)
        if form.is_valid():
            try:
                article=Article.objects.get(id=id)
            except:
                article=None
            if article:
                article.title=form.cleaned_data['title']
                article.content=form.cleaned_data['content']
                article.category=form.cleaned_data['category']
                article.permission=form.cleaned_data['permission']
                article.tag=form.cleaned_data['tag']
                article.king=form.cleaned_data['kind']
                article.save()
                messages.add_message(request,messages.SUCCESS,'修改成功')
                return redirect(reverse('my_blog-url'))
            else:
                message='修改失败'
        else:
            message='请检查输入信息'
    else:
        form=UpdateArticleForm()
    return render(request,'update_article.html',locals())
